<?php include THEMES_PATH . 'public/before_body2.phtml';?>
<link href="/statics/front/css/measure.css" rel="stylesheet">
</head>
<body>
<div class="main-width align-center">
  <div class="video-container">
    <video id="video" width="100%" height="auto" autoplay></video>
  </div>
  <div class="figure-box js-figure-box">
    <strong>180cm</strong>
    <span class="line line-head"></span>
    <img src="/statics/front/images/measure/humanoid-figure.png" alt="humanoid figure" />
    <span class="line line-foot"></span>
  </div>
  <button class="hide snapshot js-snapshot"></button>
</div>
<script src="/statics/front/js/plugins/jquery.popupBox.js"></script>
<script src="/statics/front/js/plugins/jquery.facedetection.js"></script>
<script>
$(function() {
  var clickEvent = unifyMobileDesktop.compatibleEvent({
      mobile: 'touchend',
      desktop: 'click'
    }),
    $figureBox = $('.js-figure-box'),
    convertCanvasToImg = function (canvas) {
      var img = new Image();
      img.src = canvas.toDataURL('image/png');
      return img;
    },
    scan = function (height) {
      var $line = $('.js-scanning-line'),
        timer = null,
        offsetTop = $figureBox.children('img').position().top,
        start = offsetTop - ($line.outerHeight() ? $line.outerHeight() : 7),
        end = height + offsetTop - $line.outerHeight(),
        movingDown = function() {
          clearInterval(timer);
          var top = start;
          timer = setInterval(function() {
            if (top < end) {
              top += 5;
              $line.css('top', top > end ? end : top);
            } else {
              movingUp();
            }
          }, 10);
        },
        movingUp = function() {
          clearInterval(timer);
          var top = end;
          timer = setInterval(function() {
            if (top > start) {
              top -= 5;
              $line.css('top', top < start ? start : top);
            } else {
              movingDown();
            }
          }, 10);
        },
        stop = function() {
          clearInterval(timer);
          $line.remove();
        };
      
      if ($line.length === 0) {
        $('<span class="line scanning-line js-scanning-line"></span>').appendTo($(video).parent());
        $line = $('.js-scanning-line');
      }
      $line.css('left', ($(video).parent().outerWidth() - $line.outerWidth()) / 2);
      movingDown();
      return stop;
    };

  (function() {
    var video = document.getElementById('video'),
      successCallback = function (stream) {
        if (video.mozSrcObject !== undefined) {
            video.mozSrcObject = stream;
        } else {
            video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
        }
        video.play();
      },
      errorCallback = function (error) {
        console.log('An error occurred: [CODE ' + error.code + ']');
      },
      takePhotos = function () {
        var videoWidth = video.videoWidth,
          videoHeight = video.videoHeight;
        
        if (videoWidth && videoHeight) {
          var canvas = document.createElement('canvas');
          canvas.width = videoWidth;
          canvas.height = videoHeight;
          
          $('.js-msg-popup').add($('.js-msg-mask')).remove();

          $('.js-snapshot').removeClass('hide').on(clickEvent, function(event) {
            var $thisSnapshot = $(this),
              $humanoid = $figureBox.children('img'),
              stopScanning = scan($humanoid.outerHeight()),
              humanoidWidth = $humanoid.outerWidth(),
              headWidth = humanoidWidth * .4, //头部宽度为人形轮廓宽的0.4
              headHeight = $humanoid.outerHeight() * .15, //头部高度为人形轮廓高的0.15
              headX = (humanoidWidth - headWidth) / 2, //人形轮廓中头部左边的水平坐标
              headY = 0, //人形轮廓中头部左边的垂直坐标
              faceTop,
              faceLeft,
              faceWidth,
              faceHeight,
              successCount = 0,
              timing = (new Date()).getTime(),
              timeout = 10000;

            $thisSnapshot.addClass('hide');
            var timer = setTimeout(function() {
              var callee = arguments.callee,
                $picture,
                srcArr = [];

              canvas.getContext('2d').drawImage(video, 0, 0, videoWidth, videoHeight);
              $picture = $(convertCanvasToImg(canvas));

              //照片脸部分析
              event.preventDefault();
              $picture
              .faceDetection({
                interval: 10,
                complete: function (faces) {
                  var thisImg = this;//拍照所生成的图片
                  
                  if (faces.length) {
                    faceTop = faces[0].y * faces[0].scaleY + thisImg.offset().top;
                    faceLeft = faces[0].x * faces[0].scaleX + thisImg.offset().left;
                    faceWidth = faces[0].width  * faces[0].scaleX;
                    faceHeight = faces[0].height * faces[0].scaleY;

                    if ((faceTop + faceHeight) / 2 > headY && (faceTop + faceHeight) / 2 < headY + headHeight && (faceLeft + faceWidth) / 2 > headX && (faceLeft + faceWidth) / 2 < headX + headWidth) { //确保顾客的脸的中心点在人形轮廓的头部中
                      timing = (new Date()).getTime();
                      thisImg.addClass('js-picture').appendTo('body');

                      $('<div>', {
                        'class': 'face',
                        'css': {
                          'position': 'absolute',
                          'top':      faceTop,
                          'left':     faceLeft,
                          'width':    faceWidth,
                          'height':   faceHeight
                        }
                      }).insertAfter(thisImg);
                      
                      if (successCount === 0) {
                        thisImg
                        .css('position', 'absolute')
                        .animate({
                          'top': 0,
                          'left': 0,
                          'width': 400,
                          'height': 400
                        }, 200, function() {
                          $('.face').remove();
                          successCount++;
                          timer = setTimeout(callee, 1000);
                        });
                      } else {//成功拍摄两张有脸的照片后，就取消拍照
                        $('.face').remove();
                        stopScanning();
                        $figureBox.parent().remove();
                        thisImg
                        .css('position', 'absolute')
                        .animate({
                          'top': 0,
                          'right': 0,
                          'width': 400,
                          'height': 400
                        }, 200, function() {
                          $('<p>', {
                            'class': 'align-center',
                            'css': {
                              'position': 'absolute',
                              'top': thisImg.offset().top + thisImg.outerHeight(),
                              'left': 0,
                              'width': '100%'
                            }
                          }).append('<a href="#" class="btn">下一步</a>').appendTo('body');
                        });
                      }
                      
                      if ($('.js-picture').length > 1) {
                        $('.js-picture').each(function() {
                          srcArr.push($(this).attr('src'));
                        });
                        
                        $.ajax({
                          url: '/measure/camera',
                          type: 'post',
                          data: {'image': srcArr},
                          timeout: 5000
                        })
                        .done(function(data) {
                          console.log(data);
                          console.log('照片发送成功success');
                        })
                        .fail(function() {
                          console.log('fail');
                        });
                      }
                    } else {
                      timer = setTimeout(callee, 1000);
                    }
                  } else {
                    if ((new Date()).getTime() - timing > timeout) {//如果拍照失败10秒之后，就以弹出框消息提示顾客
                      stopScanning();
                      $(document).popupBox({
                        eventType: null,
                        quickClose: true,
                        content: '<p>失败，请如图所示，站在人形轮廓区域内。</p><img src="/statics/front/images/measure/humanoid-figure.png" alt="humanoid figure" style="display:block;margin:0 auto;" />',
                        onClose: function() {
                          $thisSnapshot.removeClass('hide');
                        }
                      });
                    } else {
                      timer = setTimeout(callee, 1000);
                    }
                  }
                },
                error: function (code, message) {
                  alert('失败: ' + message);
                }
              });
            }, 1000);
          });
        } else {
          if ($('.js-msg-popup').length === 0) {
            $('<div class="popup-box show js-msg-popup" style="min-width:300px;width:30%;">请查看您的设备上是否存在可用的摄像头：如果存在，浏览器需要您允许使用摄像头（请注意浏览器的左上角区域）; 如果没有，请更换设备或选择其它量体方式。</div>').appendTo('body');
            position.fixPosition($('.js-msg-popup'));
          }
          if ($('.js-msg-mask').length === 0) {
            $('<div class="mask show js-msg-mask"></div>').appendTo('body');
          }
          setTimeout(takePhotos, 200);
        }
      };

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

    if (navigator.getUserMedia) {
      navigator.getUserMedia({'video': true}, successCallback, errorCallback);
      takePhotos();
    } else {
      alert('您的浏览器不支持拍照！请升级浏览器或更换到其它高级浏览器，如 Firefox, Chrome, Safari 等。');
    }
    $figureBox.css('width', $(video).parent().outerWidth());
  })();
});
</script>
<?php include THEMES_PATH.'public/after_body.phtml';?>